/**
 * Filename: AlbumManageActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/8 20:51
 */
package com.github.postsanf.yinian.activity;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.ClipboardManager;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopSetAvatar;
import com.github.postsanf.yinian.bean.YNAlbum;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNCommonResponse;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.Crop;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.StringUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.nostra13.universalimageloader.core.imageaware.ImageViewAware;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONObject;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.UUID;

/**
 * 相册管理页面
 */
public class AlbumManageActivity2 extends BaseActivity implements View.OnClickListener, ISkinUpdate {
    private Toolbar mToolbar;
    private YNAlbum curAlbum;
    private RelativeLayout rl_manage_invite_into;
    private RelativeLayout rl_manage_invite;
    private RelativeLayout rl_manage_name;
    private RelativeLayout rl_manage_exit;
    private RelativeLayout rl_manage_bg;
    private RelativeLayout rl_manage_member;
    private ImageView iv_manage_bg;
    private TextView tv_manage_name;
    private TextView tv_manage_class;
    private TextView tv_manage_member;
    private TextView tv_manage_invite;
    private boolean isCreator = false;
    private UploadManager mUpManager;
    private File mTempDir;
    private PopSetAvatar mpopSetAvatar;
    private ProgressDialog mProgressDialog;
    private String albumName_alert;
    private String bgUrl;
    private TextView tv_album_exit;
    private String tip;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_album_manage2);
        BaseApplication.getInstance().mActivitys.add(this);
        curAlbum = YNSingleton.getInstance().getCurAlbum();
        mUpManager = application.getUploadManager();
        mTempDir = new File(Environment.getExternalStorageDirectory(), "Temp");
        if (!mTempDir.exists()) {
            mTempDir.mkdirs();
        }
        initView();
    }

    private void initView() {
        mpopSetAvatar = new PopSetAvatar(AlbumManageActivity2.this, itemsOnClick, itemsOnTouch);
        mToolbar = (Toolbar) findViewById(R.id.album_manage_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.btn_expend_white);
        rl_manage_member = (RelativeLayout) findViewById(R.id.rl_manage_member);
        rl_manage_bg = (RelativeLayout) findViewById(R.id.rl_manage_bg);
        rl_manage_name = (RelativeLayout) findViewById(R.id.rl_manage_name);
        rl_manage_invite = (RelativeLayout) findViewById(R.id.rl_manage_invite);
        rl_manage_invite_into = (RelativeLayout) findViewById(R.id.rl_manage_invite_into);
        rl_manage_exit = (RelativeLayout) findViewById(R.id.rl_manage_exit);
        iv_manage_bg = (ImageView) findViewById(R.id.iv_manage_bg);
        tv_manage_name = (TextView) findViewById(R.id.tv_manage_name);
        tv_manage_class = (TextView) findViewById(R.id.tv_manage_class);
        tv_manage_invite = (TextView) findViewById(R.id.tv_manage_invite);
        tv_album_exit = (TextView) findViewById(R.id.tv_album_exit);
        tv_manage_member = (TextView) findViewById(R.id.tv_manage_member);
        if (StringUtils.isOfficialGroup(curAlbum.getGtype())) {
            rl_manage_invite_into.setVisibility(View.VISIBLE);
            rl_manage_member.setVisibility(View.GONE);
        }
        imageLoader.displayImage(curAlbum.getGpic(), new ImageViewAware(iv_manage_bg, false), ImageOptHelper.getCornerOptions(2));
        tv_manage_name.setText(curAlbum.getGname());
        tv_manage_class.setText(curAlbum.getGtype());
        tv_manage_invite.setText(curAlbum.getGinvite());
        tv_manage_member.setText(curAlbum.getGnum() + "人");
        if (curAlbum.getGcreator() != null && curAlbum.getGcreator().equals(String.valueOf(application.getCurID()))) {
            isCreator = true;
            tip = "解散";
            tv_album_exit.setText("解散圈子");
        } else {
            isCreator = false;
            tip = "退出";
        }
        rl_manage_member.setOnClickListener(this);
        rl_manage_invite_into.setOnClickListener(this);
        rl_manage_bg.setOnClickListener(this);
        rl_manage_name.setOnClickListener(this);
        rl_manage_invite.setOnClickListener(this);
        rl_manage_exit.setOnClickListener(this);
//        findViewById(R.id.rl_one_invite).setOnClickListener(this);
    }

    //	头像
    private View.OnTouchListener itemsOnTouch = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int height = mpopSetAvatar.mMenuView.findViewById(R.id.pop_setuser_advatar_layout).getTop();
            int y = (int) event.getY();
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (y < height) {
                    mpopSetAvatar.dismiss();
                }
            }
            return true;
        }
    };

    // 头像监听
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            mpopSetAvatar.dismiss();
            switch (v.getId()) {
                case R.id.btn_setuser_take_photo:
                    ImageUtils.pickImageFromCamera(AlbumManageActivity2.this);
                    break;
                case R.id.btn_setuser_pick_photo:
                    ImageUtils.pickImageFromAlbum(AlbumManageActivity2.this);
                    break;
                case R.id.btn_setuser_cancel_photo:
                    break;
            }
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_manage_member:
                Intent mintent = new Intent(this, MemberActivity.class);
                mintent.putExtra(CommonConstants.YNDATAS, curAlbum);
                startActivity(mintent);
                break;
            case R.id.rl_manage_invite_into:
                Intent iintent = new Intent(this, InviteChooseActivity.class);
                iintent.putExtra(CommonConstants.YNDATAS, curAlbum);
                startActivity(iintent);
                break;
            case R.id.rl_manage_bg:
                if (StringUtils.isOfficialGroup(curAlbum.getGtype()) && !(String.valueOf(application.getCurID()).equals(getString(R.string.numberofme)))) {
                    return;
                }
                mpopSetAvatar.showAtLocation(AlbumManageActivity2.this.findViewById(R.id.ll_album_manage_content), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                ((TextView) mpopSetAvatar.mMenuView.findViewById(R.id.btn_alert_avatar_title)).setText("修改圈子背景");
                break;
            // 修改组名
            case R.id.rl_manage_name:
                String tab = getString(R.string.numberofme);
                if (StringUtils.isOfficialGroup(curAlbum.getGtype()) && !(String.valueOf(application.getCurID()).equals(tab))) {
                    return;
                }
                Intent intent = new Intent(this, AlertNameActivity.class);
                intent.putExtra(CommonConstants.YNDATAS, curAlbum.getGname());
                startActivityForResult(intent, CommonConstants.REQ_ALERT_GNAME);
                break;
            case R.id.rl_manage_invite:
                ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                clip.setText(tv_manage_invite.getText().toString().trim());
                showToast("复制邀请码成功");
                break;
            case R.id.rl_manage_exit:
                new AlertDialog.Builder(this).setMessage("确定要" + tip + "该圈子吗？")
                        .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                doExitAlbum();
                            }
                        })
                        .setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        }).show();
                break;
//            case R.id.rl_one_invite:
//                intent2Activity(InviteCodectivity.class);
//                break;
        }
    }

    // 退组or删除
    private void doExitAlbum() {
        String address = getString(R.string.ynDeleteGroup);
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        if (!isCreator) {
            address = getString(R.string.ynQuitGroup);
        }
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(application.getCurID()));
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(curAlbum.getGroupid()));
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + address).setMethod(HttpMethods.Post).setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resQuitGroup = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resQuitGroup.getCode())) {
                            Intent intent = new Intent();
                            intent.putExtra(CommonConstants.REQ_CODE, 1);
                            setResult(RESULT_OK, intent);
                            //发送广播,通知更新个人信息
                            Intent mIntent = new Intent(ACTIONs.actionGroupQuit);
                            sendBroadcast(mIntent);
                            finish();
                        } else {
                            showToast(resQuitGroup.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 处理图像剪切结果
    private void handleCrop(int resultCode, Intent result) {
        if (resultCode == Activity.RESULT_OK) {
            bgUrl = ImageUtils.getImageAbsolutePath19(this, Crop.getOutput(result));
            imageLoader.displayImage("file:///" + bgUrl, iv_manage_bg, ImageOptHelper.getCornerOptions(2));
            getToken();
        } else if (resultCode == Crop.RESULT_ERROR) {
            showToast("处理图片失败");
        }
    }

    // 开始剪切过程
    private void beginCrop(Uri source) {
        String fileName = "Temp_" + String.valueOf(System.currentTimeMillis()) + ".png";
        File cropFile = new File(mTempDir, fileName);
        Uri outputUri = Uri.fromFile(cropFile);
        new Crop(source).output(outputUri).setCropType(false).start(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_FROM_ALBUM:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                Uri imageUri = data.getData();
                beginCrop(imageUri);
                break;
            case ImageUtils.REQUEST_CODE_FROM_CAMERA:
                if (resultCode == RESULT_CANCELED) {
                    ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera);
                } else {
                    Uri imageUriCamera = ImageUtils.imageUriFromCamera;
                    beginCrop(imageUriCamera);
                }
                break;
            case Crop.REQUEST_CROP:
                handleCrop(resultCode, data);
                break;
            //  修改相册名回调
            case CommonConstants.REQ_ALERT_GNAME:
                if (resultCode == RESULT_CANCELED) {
                    return;
                }
                    albumName_alert = data.getStringExtra(CommonConstants.REQ_DATA);
                    tv_manage_name.setText(albumName_alert);
                    alertGroupName(albumName_alert);
                break;
            default:
                break;
        }
    }

    // 获取上传Token
    private void getToken() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            getAvatarAddress();
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 获取七牛云头像地址
    private void getAvatarAddress() {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        String prefix = bgUrl.substring(bgUrl.lastIndexOf(".") + 1);
        final String imgName = UUID.randomUUID().toString() + "." + prefix;
        mUpManager.put(bgUrl, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject res) {
                        doBgPost(key, imgName);
                        mProgressDialog.dismiss();
                    }
                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            public void progress(String key, double percent) {
                            }
                        }, null));
    }

    // 修改相册背景
    private void doBgPost(String key, final String iName) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_IDD, String.valueOf(YNSingleton.getInstance().getCurAlbum().getGroupid()));
        mParam.put(CommonConstants.YNS_URL, key);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynModifyGroupPic))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resAlertBg = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resAlertBg.getCode())) {
                            YNSingleton.getInstance().getCurAlbum().setGpic(CommonConstants.YNQNURL + iName);
                            Intent mIntent = new Intent(ACTIONs.actionAlertGPic);
                            sendBroadcast(mIntent);
                            showToast("修改成功");
                        } else {
                            imageLoader.displayImage(curAlbum.getGpic(), iv_manage_bg, ImageOptHelper.getCornerOptions(2));
                            showToast("修改失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    // 修改相册名
    private void alertGroupName(final String gName) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_GROUP_ID, String.valueOf(curAlbum.getGroupid()));
        mParam.put(CommonConstants.YNS_GROUP_NAME, gName);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynModifyGroupName)).setMethod(HttpMethods.Post).setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNCommonResponse resAlertGroupName = gson.fromJson(s, YNCommonResponse.class);
                        if (ReqUtils.isSuccess(resAlertGroupName.getCode())) {
                            YNSingleton.getInstance().getCurAlbum().setGname(gName);
                            Intent mIntent = new Intent(ACTIONs.actionAlertGName);
                            mIntent.putExtra("gName", gName);
                            sendBroadcast(mIntent);
                            showToast("修改成功");
                        } else {
                            tv_manage_name.setText(curAlbum.getGname());
                            showToast("修改失败");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void updateTheme() {
        if (mToolbar != null) {
            try {
                Resources mResource = SkinPackageManager.getInstance(this).mResources;
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", "drawable", "com.github.postsanf.skinby")));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", "color", "com.github.postsanf.skinby")));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", "color", "com.github.postsanf.skinby")));
                tv_album_exit.setTextColor(mResource.getColor(mResource.getIdentifier("yncolor", "color", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_take_photo.setBackground(mResource.getDrawable(mResource.getIdentifier("btn_invite_bg_sel", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_pick_photo.setBackground(mResource.getDrawable(mResource.getIdentifier("btn_invite_bg_sel", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_cancel.setBackground(mResource.getDrawable(mResource.getIdentifier("btn_invite_bg_sel", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_take_photo.setTextColor(mResource.getColorStateList(mResource.getIdentifier("btn_txtcolor_switch2theme", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_pick_photo.setTextColor(mResource.getColorStateList(mResource.getIdentifier("btn_txtcolor_switch2theme", "drawable", "com.github.postsanf.skinby")));
                mpopSetAvatar.btn_cancel.setTextColor(mResource.getColorStateList(mResource.getIdentifier("btn_txtcolor_switch2theme", "drawable", "com.github.postsanf.skinby")));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BaseApplication.getInstance().mActivitys.remove(this);
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        if (SkinPackageManager.getInstance(this).mResources != null) {
            updateTheme();
        }
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
